package Concurrency4_GeekTime.Chapter23_Future;

import java.util.concurrent.*;

/**
 * 功能说明：模拟烧水泡茶程序
 * 分工如下:
 * Thread1: 洗水壶, 烧水, 泡茶
 * Thread2: 洗茶壶, 洗茶杯, 拿茶叶
 * 实现方式; 线程池+Future
 * 开发人员：@author MaLi
 */
public class Example1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        FutureTask<String> t2 = new FutureTask<>(new Task2());
        FutureTask<String> t1 = new FutureTask<>(new Task1(t2));
        Future<?> submit = service.submit(t1);
        service.submit(t2);
        System.out.println(t1.get());
        System.out.println("submit.get -->"+submit.get());
        service.shutdownNow();
    }


    private static class Task1 implements Callable<String> {
        //获取不到的传进来
        private FutureTask<String> ft2Result;

        public Task1(FutureTask<String> ft2Result) {
            this.ft2Result = ft2Result;
        }

        @Override
        public String call() throws Exception {
            try {
                System.out.println("洗水壶");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("烧水");
                TimeUnit.SECONDS.sleep(2);
                //需要线程2的执行结果
                String tea = ft2Result.get();
                System.out.println("拿到茶叶:" + tea + " --> 泡茶");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "等着喝茶...";
        }
    }

    private static class Task2 implements Callable<String> {

        @Override
        public String call() throws Exception {
            try {
                System.out.println("洗茶壶");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("洗茶杯");
                TimeUnit.SECONDS.sleep(2);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "龙井";
        }
    }
}

